#include <stdio.h>
#include <stdlib.h>
#include "expressao_melhorada_aula2.h"

int pos = 0;
char exp[20];

/* Exp -> dig R     {Exp.val = dig.val + R.val}
   R -> + dig R1 |   {R.val = dig.val + R1.val}
        - dig R1 |   {R.val = dig.val - R1.val}
		* dig R1 |   {R.val = dig.val * R1.val}
		/ dig R1 |   {R.val = dig.val / R1.val}
        vazio        {R.val = 0} */

int R(int Rh, int *Rs)
{
	int Tval, R1h, R1s;

	char op = exp[pos];

	if(op == '+' || op == '-' || op == '*' || op == '/')
	{
		pos++;
		if(exp[pos] >= '0' && exp[pos] <= '9')
		{
			Tval = exp[pos] - '0';
			
			if(op == '+') R1h = Rh + Tval;
			if(op == '-') R1h = Rh - Tval;
			if(op == '/') R1h = Rh / Tval;
			if(op == '*') R1h = Rh * Tval;
			
			pos++;
			if(R(R1h, &R1s))
			{
				*Rs = R1s;
			}
			else
			{
				*Rs = R1h;
			}
			return 1;
		}
		else if(exp[pos] == '(')
		{
			pos++;
			int valor;
			if(E(&valor))
			{				
				if(op == '+') *Rs = Rh + valor;
				if(op == '-') *Rs = Rh - valor;
				if(op == '/') *Rs = Rh / valor;
				if(op == '*') *Rs = Rh * valor;
				return 1;
			}
			else
			{
				return 0;
			}
		}
		else
		{
			return 0;
		}
	}
	else if(op == ')')
	{
		*Rs = Rh;
		return 1;
	}
	else 
	{
		return 0;
	}
}

int E(int *Eval)
{
	int Rh, Rs, Tval;
	if(exp[pos] >= '0' && exp[pos] <= '9')
	{
		Tval = exp[pos] - '0';
		pos++;
		Rh = Tval;
		
		if(R(Rh, &Rs)) 
		{
			*Eval = Rs;
			return 1;
		}
	}

	return 0;
}

int main()
{
	int valor;
	printf("Entre com a expressao a avaliar:");
	fflush(stdin);
	scanf("%s",exp);
	if(E(&valor))
	{
		printf("A expressao vale %d\n",valor);
	}
	else
	{
		printf("Expressao invalida");
	}

	system("pause");   
}

